package com.atao.baokede.service.serviceImpl;

import com.atao.baokede.mapper.CartMapper;
import com.atao.baokede.pojo.Cart;
import com.atao.baokede.service.CartService;
import com.atao.baokede.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import static com.atao.baokede.constant.ItemConstant.STATUS_ON_SALE;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    /**
     * 获取当前用户ID（从ThreadLocal中获取）
     */
    private Long getCurrentUserId() {
        Map<String, Object> userMap = ThreadLocalUtil.get();
        return ((Number) userMap.get("id")).longValue();
    }

    @Override
    public List<Cart> findByUserId() {
        Long userId=getCurrentUserId();
        return cartMapper.findByUserId(userId);
    }


    @Override
    public void insert(Cart cart) {
        // 设置当前用户ID
        cart.setUserId(getCurrentUserId());
        cart.setStatus(0);
        cartMapper.insert(cart);
    }


    @Override
    public void updateNumByItemId(Long cartId, Long num) {
        cartMapper.updateNumByUserIdAndItemId(cartId, num);
    }


    @Override
    public void deleteByCartId(Long cartId) {
        cartMapper.deleteByCartId(cartId);
    }

    @Override
    public Long getTotalItemCountByUserId() {
        return cartMapper.getTotalItemCountByUserId(getCurrentUserId());
    }

    @Override
    public BigDecimal getTotalPrice(List<Long> cartIds) {
        return cartMapper.getTotalPrice(cartIds);
    }


    @Override
    public List<Cart> searchByName(String keyword) {
        return cartMapper.searchByName(keyword);
    }

    @Override
    public List<Cart> findByIds(List<Long> ids) {
        return cartMapper.findByCartIds(ids);
    }

    @Override
    public void deleteByCartIds(List<Long> ids) {
        cartMapper.deleteByCartIds(ids);
    }

    @Override
    public void disableCartItem(Long itemId) {
        cartMapper.disableCartItem(itemId);
    }

    @Override
    public void disableCartItems(List<Long> itemIds) {
        cartMapper.disableCartItems(itemIds);
    }

    @Override
    public void enableCartItems(List<Long> itemIds) {
        cartMapper.enableCartItems(itemIds);
    }

    @Override
    public Cart findByItemId(Long itemId) {
        return cartMapper.findByItemId(itemId);
    }

}
